package com.zhiziai.aiproxy.service;


import cn.hutool.core.collection.CollectionUtil;
import com.google.common.base.Preconditions;
import com.zhiziai.aiproxy.constants.ProxyType;
import com.zhiziai.aiproxy.constants.UploadType;
import com.zhiziai.aiproxy.dto.MidJourneyImgDto;
import com.zhiziai.aiproxy.dto.Text2ImgDto;
import com.zhiziai.aiproxy.utils.OpenAIUtil;
import com.zhiziai.aiproxy.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author: liuxinyu06
 * @description:
 * @create: 2022-04-07
 **/
@Slf4j
@Service
public class AIProxyServiceImpl{

    @Autowired
    private MidjourneyServiceImpl midjourneyService;
    @Autowired
    private UploadService uploadService;

    public List<Text2ImgDto> text2ImgEncrypt(Long userId, String prompt, Integer genNum, String sign) throws Exception{
        Preconditions.checkArgument(genNum != null && genNum > 0 && genNum <=4, "genNum error");
        Preconditions.checkArgument(userId != null && StringUtils.isNotEmpty(prompt) && StringUtils.isNotEmpty(sign), "param error");
        String calSign = SignUtil.buildSign(userId+"",prompt,genNum+"");
        Preconditions.checkArgument(StringUtils.isNotEmpty(calSign) && calSign.equals(sign),"auth error");
        List<MidJourneyImgDto> midJourneyImgDtos = midjourneyService.imagineGen(userId,prompt,genNum);
        if(CollectionUtil.isNotEmpty(midJourneyImgDtos)){
            return midJourneyImgDtos.stream().map(midJourneyImgDto -> {
                Text2ImgDto text2ImgDto = new Text2ImgDto();
                BeanUtils.copyProperties(midJourneyImgDto,text2ImgDto);
                text2ImgDto.setProxyType(ProxyType.MIDJOURNEY.getType());
                return text2ImgDto;
            }).collect(Collectors.toList());
        }else{
            //dalle2兜底
            List<String> dalleImgUrls = dalleGenImg(userId,prompt,genNum,"1024x1024");
            return dalleImgUrls.stream().map(cosUrl ->
                            Text2ImgDto.builder().imgUrl(cosUrl).proxyType(ProxyType.DALLE.getType()).build())
                    .collect(Collectors.toList());
        }
    }


    public List<String> dalleGenImg(Long userId, String prompt, Integer genNum, String resulotionRate) throws Exception {
        List<String> cosUrls = new ArrayList<>();
        List<String> urls = OpenAIUtil.dalleGen(prompt, genNum, resulotionRate);
        if(CollectionUtil.isNotEmpty(urls)){
            List<CompletableFuture<String>> cfs = urls.stream().map(url -> CompletableFuture.supplyAsync(() -> {
                try {
                    return uploadService.upload(userId,url, UploadType.DALLE.getType());
                } catch (Exception e) {
                    log.error("dalleGenImg upload error " ,e);
                }
                return null;
            })).collect(Collectors.toList());
            cfs.stream().map(CompletableFuture::join).filter(Objects::nonNull).forEach(cosUrls::add);
        }
        return cosUrls;
    }


}
